package com.example.fw;

import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;


public class ContactHelper extends HelperWithWebDriverBase {
	
	//private Contacts contactCache;
	private	Contacts contactModel;	// lesson 7 - 57:00, model instead of cache
	private int nextContactId;

	public ContactHelper(ApplicationManager manager) {
		super(manager);										// init super class HelperWithWebDriverBase
		contactModel = getContacts();
		nextContactId = Integer.parseInt(manager.getHibernateHelper().getNextContactId());
	}
	
	public Contacts getContacts() {
		if (contactModel == null)	{
			contactModel = manager.getHibernateHelper().getContacts();
		}
		return contactModel;

//		if (contactCache == null)	{
//			buildContactCache();
//		}
//		return contactCache;
	}
		
	public Contacts getUiContacts() {		// lesson 7 ~ 72:00
		HashSet<ContactObject> set = new HashSet<ContactObject>();
		manager.getNavigationHelper().openMainPage();
		WebElement form = findElements(By.tagName("form")).get(2);
		List<WebElement> checkboxes = form.findElements(By.name("selected[]"));
		for (WebElement checkbox : checkboxes) {
			String title = checkbox.getAttribute("title");
			Pattern p = Pattern.compile(".*\\((.*)\\)");	// lesson 4 47:00 - find all elements inside ( ) - firstname & lastname
			Matcher m = p.matcher(title);
			if (m.matches())	{
				title = m.group(1);
			}
			
			int endIndex = title.lastIndexOf(' ');
			String firstName = title.substring(0, endIndex);
			String lastName = title.substring(endIndex + 1, title.length());
			
			ContactObject contact = new ContactObject()
								.setName(firstName)
								.setLastname(lastName)
								.setContactId(checkbox.getAttribute("value"));
			set.add(contact);
		}
		return new Contacts(set);
	}
	
	
	
	
	
	
//	public ContactObject getUiContactData(ContactObject contact) {
//		initContactModification(contact);
//		ContactObject contactFromUi = new ContactObject()
//			.setName(firstName)
//			.setLastname(lastName)		// locators???
//			.setContactId(checkbox.getAttribute("value"));
//
//		return contactFromUi;
//	}
	
	
	
	
	
	
	
	
	
//	private void buildContactCache()	{ 
//		HashSet<ContactObject> set = new HashSet<ContactObject>();
//		manager.getNavigationHelper().openMainPage();
//		WebElement form = findElements(By.tagName("form")).get(2);
//		List<WebElement> checkboxes = form.findElements(By.name("selected[]"));
//		for (WebElement checkbox : checkboxes) {
//			String title = checkbox.getAttribute("title");
//			Pattern p = Pattern.compile(".*\\((.*)\\)");	// lesson 4 47:00 - find all elements inside ( ) - firstname & lastname
//			Matcher m = p.matcher(title);
//			if (m.matches())	{
//				title = m.group(1);
//			}
//			
//			int endIndex = title.lastIndexOf(' ');
//			String firstName = title.substring(0, endIndex);
//			String lastName = title.substring(endIndex + 1, title.length());
//			
//			ContactObject contact = new ContactObject()
//								.setName(firstName)
//								.setLastname(lastName)
//								.setContactId(checkbox.getAttribute("value"));
//			set.add(contact);
//		}
//		contactCache = new Contacts(set);
//	}

//	public Set<ContactObject> getContacts() {
//		manager.getNavigationHelper().openMainPage();
//		WebElement form = findElements(By.tagName("form")).get(2);
//		List<WebElement> checkboxes = form.findElements(By.name("selected[]"));
//		Set<ContactObject> contacts = new HashSet<ContactObject>();
//		for (WebElement checkbox : checkboxes) {
//			String title = checkbox.getAttribute("title");
//			//	lesson 3 - 35:00
//			if (!title.isEmpty()) {
//                 //
//                 title = title.substring("Select (".length(),
//                                 title.length() - ")".length());
//                 String[] splitted = title.trim().split(" ");
//                 //
//                 ContactObject contact = new ContactObject().setName(splitted[0]).setLastName(splitted[1]).setId(checkbox.getAttribute("value"));
//			contacts.add(contact);
//			}
//		}
//		return contacts; 
//	}

	public void createContact(ContactObject contactObject) {
		manager.getNavigationHelper().openMainPage();
		addNewContact();
		fillContactForm(contactObject, true);
		submitContactCreation();
		manager.getNavigationHelper().gotoHomePage();
		//buildContactCache();
		contactObject.setContactId("" + nextContactId);
		nextContactId = nextContactId + 1;
		contactModel = contactModel.withAdded(contactObject);

	}

	public void modifyContact(ContactObject contactBeforeModification, ContactObject contactAfterModification) {
		manager.getNavigationHelper().openMainPage();
		initContactModification(contactBeforeModification);
		fillContactForm(contactAfterModification, false);
		submitContactUpdate();
		manager.getNavigationHelper().gotoHomePage();
		//buildContactCache();
		contactModel = contactModel.withOut(contactBeforeModification).withAdded(contactAfterModification);
	}

	public void deleteContact(ContactObject someContact) {
		manager.getNavigationHelper().openMainPage();
		initContactModification(someContact);		
		submitContactDelete();
		manager.getNavigationHelper().gotoHomePage();
		//buildContactCache();
		contactModel = contactModel.withOut(someContact);
	}

	private void fillContactForm(ContactObject contactObject, boolean fillGroup) {
		type(By.name("firstname"), contactObject.firstname);
		type(By.name("lastname"), contactObject.lastname);
		type(By.name("address"), contactObject.address);
		type(By.name("home"), contactObject.ph_home);
		type(By.name("mobile"), contactObject.ph_mobile);
		type(By.name("work"), contactObject.ph_work);
		type(By.name("email"), contactObject.email);
		type(By.name("email2"), contactObject.email2);
		select(By.name("bday"), contactObject.bday);
		select(By.name("bmonth"), contactObject.bmonth);
		type(By.name("byear"), contactObject.byear);
		if (fillGroup)	{
			select(By.name("new_group"), contactObject.group);
		}	else {
			// ...
		}
//		if (driver.findElements(By.name("new_group")).size() > 0)	{
//			selectVisible(By.name("new_group"), contactObject.group);
//		}
		type(By.name("address2"), contactObject.address2);
		type(By.name("phone2"), contactObject.phone2);
	}

	private void addNewContact() {
		findElement(By.linkText("add new")).click();
	}

	private void submitContactCreation() {
		driver.findElement(By.name("submit")).click();
	}

	private void submitContactUpdate() {
		driver.findElement(By.name("update")).click();	//<input type="submit" value="Update" name="update">
	}

	private void submitContactDelete() {
		driver.findElement(By.xpath("(//input[@name='update'])[2]")).click();	//<input type="submit" value="Delete" name="update">
	}

	private void initContactModification(ContactObject someContact) {

		WebElement form = findElements(By.tagName("form")).get(2);
		List<WebElement> checkboxes = form.findElements(By.name("selected[]"));
		int i = 1;
		for (WebElement checkbox : checkboxes) {
			String title = checkbox.getAttribute("title");
			if (!title.isEmpty()) {
                 title = title.substring("Select (".length(), title.length() - ")".length());
                 String[] splitted = title.trim().split(" ");
                 if (splitted[0].equals(someContact.firstname) && splitted[1].equals(someContact.lastname)) {
         			findElement(By.xpath("(//img[@alt='Edit'])[" + i + "]")).click();			//findElement(By.cssSelector("img[alt=\"Edit\"]")).click();
         			return;
         		}
			}
			i++;
		}	
	}
	
	public int generateRandomNumberBetween(int start, int end) {
		return new Random().nextInt(end - start) + start;
	}
}
